# -*- coding: utf-8 -*-
#import pycurl
#import StringIO

import sys
import re
import urllib
import urllib2
import sqlite3
import os
import logging

class mcLogger():
	
	_instances = {}

	@classmethod
	def getInstance(cls, name):
		if name not in cls._instances:			
			cls._instances[name] = logging.getLogger(name)
			hdlr = logging.FileHandler('logs/' + name + '.log')
			formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
			hdlr.setFormatter(formatter)
			cls._instances[name].addHandler(hdlr)
			cls._instances[name].setLevel(logging.DEBUG)
			cls._instances[name].info('Init loggin ['+ name + '] ...')
		return cls._instances[name]
	
class mcScrapper:

	@classmethod
	def get(cls,theurl, COOKIEFILE = None, headers = None):
		return cls.request(theurl, None, COOKIEFILE, headers) ['srt']

	@classmethod
	def post(cls,theurl, txtdata, COOKIEFILE = None, headers = None):
		return cls.request(theurl, txtdata, COOKIEFILE, headers)['srt']

	@classmethod
	def down(cls, theurl, COOKIEFILE = None, headers = None, tofile = None):
		return cls.request(theurl, None, COOKIEFILE, headers, tofile)['srt']

	@classmethod
	def request(cls, theurl, txdata, COOKIEFILE = None, headers = None, tofile = None):

		# COOKIEFILE = None .... not use
		#if COOKIEFILE = None:
		#	COOKIEFILE = 'cookies.lwp'
		
		result = {
			'str' :  '',
			'url' : '' 
			}
		
		import os.path
		
		logger = mcLogger.getInstance('scrapper')
		
		logger.debug("URL   :" + theurl)
		if not txdata == None:
			logger.debug("DATA :" + txdata)
		
		cj = None
		ClientCookie = None
		cookielib = None

		try:                                    # Let's see if cookielib is available
			import cookielib            
		except ImportError:
			pass
		else:
			import urllib2    
			urlopen = urllib2.urlopen
			cj = cookielib.LWPCookieJar()       # This is a subclass of FileCookieJar that has useful load and save methods
			Request = urllib2.Request

		if not cookielib:                   # If importing cookielib fails let's try ClientCookie
			try:                                            
				import ClientCookie 
			except ImportError:
				import urllib2
				urlopen = urllib2.urlopen
				Request = urllib2.Request
			else:
				urlopen = ClientCookie.urlopen
				cj = ClientCookie.LWPCookieJar()
				Request = ClientCookie.Request

		####################################################
		# We've now imported the relevant library - whichever library is being used urlopen is bound to the right function for retrieving URLs
		# Request is bound to the right function for creating Request objects
		# Let's load the cookies, if they exist. 
		
		if cj != None:                                  # now we have to install our CookieJar so that it is used as the default CookieProcessor in the default opener handler
			if not COOKIEFILE == None:
				if os.path.isfile(COOKIEFILE):
					cj.load(COOKIEFILE)
				if cookielib:
					opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
					urllib2.install_opener(opener)
				else:
					opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj))
					ClientCookie.install_opener(opener)

		# If one of the cookie libraries is available, any call to urlopen will handle cookies using the CookieJar instance we've created
		# (Note that if we are using ClientCookie we haven't explicitly imported urllib2)
		# as an example :
		
		#theurl = url_base        # an example url that sets a cookie, try different urls here and see the cookie collection you can make !
		#txdata = None                                                                           # if we were making a POST type request, we could encode a dictionary of values here - using urllib.urlencode
		txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}          # fake a user agent, some websites (like google) don't like automated exploration
		output=""
		try:
			req = Request(theurl, txdata, txheaders)            # create a request object
			if headers:
				for h in headers:
					req.add_header(h, headers[h])
			
			handle = urlopen(req)                               # and open it to return a handle on the url

		except IOError, e:
			logger.debug('We failed to open "%s".' % theurl)
			if hasattr(e, 'code'):
				logger.debug('We failed with error code - %s.' % e.code)
		else:
			logger.debug('Here are the headers of the page :')						
			# handle.read() returns the page, handle.geturl() returns the true url of the page fetched (in case urlopen has followed any redirects, which it sometimes does)
					
			result['url'] = handle.geturl()
			
			logger.debug( result['url'] )
			logger.debug( handle.info() )

			if tofile == None:
				logger.debug("Getting content.")				
				output = handle.read()
			else:
				logger.debug("Saving to file " + tofile)
								
				f = open(tofile, 'wb')

				i=0
				block_sz = 8192
				while True:
					buffer = handle.read(block_sz)
					if not buffer:
						break
					
					sys.stdout.write(".")
					if i == 10:
						sys.stdout.write('\r')
						i=0
					sys.stdout.flush() 
					f.write(buffer)

					i=i+1
				f.close()
				print ""
				

		if cj == None:
			logger.debug("We don't have a cookie library available - sorry.")
			logger.debug("I can't show you any cookies.")			
		else:
			logger.debug('These are the cookies we have received so far :')
			for index, cookie in enumerate(cj):
				logger.debug( str(index) + '  :  ' + str(cookie) )				
			if not COOKIEFILE == None:
				cj.save(COOKIEFILE)                     # save the cookies again
				
		result['srt'] = output
		return result

		
class mcBase:
	logger = None

	@classmethod
	def init(cls):
		cls._loadLogger()
		cls.data = mcData()

	@classmethod
	def _loadLogger(cls):

		import logging

		cls.logger = logging.getLogger('maxcinema')
		hdlr = logging.FileHandler('maxcinema.log')
		formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
		hdlr.setFormatter(formatter)
		cls.logger.addHandler(hdlr)

		cls.logger.setLevel(logging.DEBUG)

		cls.logger.info('Iniciando Maxcinema ...')

		return cls.logger

class mcData:

	dbconn = None

	rx_504 = None
	rx_502 = None

	def __init__(self):

		self.dbconn = sqlite3.connect('app.db')

		self.rx_504 = re.compile('504 Gateway Time-out')
		self.rx_502 = re.compile('502 Bad Gateway')

	def get(self, url, cf = None , headers = None):
		logger = mcLogger.getInstance('mcdata')
		salida = ""
		intent = 10
		i=0
		while i < intent:			
			logger.debug("before GET " + url)
			salida = mcScrapper.get(url, cf, headers)
			logger.debug("after GET ")
			logger.debug(salida)
			m = re.search(self.rx_504 , salida)
			if m != None:
				i = i + 1
				logger.debug("Reintento ... #" + str(i)  + " (Gateway Time-out)")
			else:
				m = re.search( self.rx_502, salida)
				if m != None:
					i = i + 1
					logger.debug("Reintento ... #" + str(i) + " (Bad Gateway)")
				else:
					i = intent
		return salida

	def post(self,url, post, cf = None, headers = None):
		logger = mcLogger.getInstance('mcdata')
		logger.debug("before POST " + url)		
		salida = mcScrapper.post(url, post, cf, headers)
		logger.debug("after POST ")
		return salida

	def down(self, url, output, cf = "cookies.txt" , headers = None):
			
		user_agent = 'Mozilla/4.0 (compatible: MSIE 6.0)'				

		req = urllib2.Request(url)
		req.add_header('User-Agent', user_agent)		

		import fileinput
		import os
		if os.path.exists(cf):
			for line in fileinput.input(cf):
				req.add_header('Set-Cookie', line)
			

		if headers:
			for h in headers:
				req.add_header(h, headers[h])

		response = urllib2.urlopen(req)		
		
		f = open(output, 'wb')
		meta = response.info()
		file_size = int(meta.getheaders("Content-Length")[0])
		
		print "Downloading: %s Bytes: %s" % (output, file_size)

		file_size_dl = 0
		block_sz = 8192
		while True:
			buffer = response.read(block_sz)
			if not buffer:
				break

			file_size_dl += len(buffer)
			f.write(buffer)
			status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
			status = status + chr(8)*(len(status)+1)
			print status,

		f.close()		
		
class mcMovie:

	###############################
	##	Public Methods
	###############################

	def __init__ (self, service=None, id=None):
			
		##	Publics fields
	
		self.service		= ""

		self.id 		= ""
		self.title		= ""
		self.original_title	= ""
		self.description	= ""

		self.url		= ""
		self.cover_url		= ""

		self.sources	= []
		self.subtitles	= []		
		
		self.audios	= []
		
		##	Protecteds fields
	
		self._exist_in_db    = False
		self._mcData = mcData()
		self._logger = None
		
		
		if service != None:
			self.service = service

		if id != None:
			self.id = id

		if service != None and id != None:
			
			#Load Info
			if not self.dbLoadInfo() :			
				self.loadInfo()

			#Load Sources
			if not self.dbLoadSources() :
				self.loadSources()

			#Subtitles
			if not self.dbLoadAudios() :
				self.loadAudios()
			
			#Subtitles
			if not self.dbLoadSubtitles() :
				self.loadSubtitles()
				


	def loadInfo(self):
		self.dbStoreInfo()

	def loadSources(self):
		#self.dbDeleteAllSources()
		for s in self.sources:
			self.dbStoreSource(s)

	def loadSubtitles(self):
		#self.dbDeleteAllSources()
		for s in self.subtitles:
			self.dbStoreSubtitle(s)

	def loadAudios(self):
		#self.dbDeleteAllSources()
		for s in self.audios:
			self.dbStoreAudio(s)

	
	def downSource(self, source):
		
		file_name = self.title + ".mp4"
		
		if source.server == "wupload":
			from down_wupload import wuploadDown
			d = wuploadDown()
			d.run(source.url, file_name)
			
		if source.server == "bayfiles":
			from down_bayfiles import bayfilesDown
			d = bayfilesDown()
			d.run(source.url, file_name)
			
	def downSubtitle(self, lang_code):
		pass

	def getDefinitions(self):
		conn = self._mcData.dbconn

		c = conn.cursor()		
		
		query = "select distinct definition from sources where id = '%s'" % self.id
		
		c.execute( query )

		result=[]
		for row in c:
			result.append(row[0])

		c.close()
		
		return result
		

	###############################
	##	Storage Methods
	###############################

	def dbStoreInfo(self):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table
		c.execute('''create table if not exists movies
		(service text, id text, title text, original_title text, description text, url text, cover_url text, primary key(service, id) )''')

		# Insert a row of data
		c.execute("replace into movies values ( ?, ?, ?, ?, ?, ?, ?)" , (self.service, self.id, self.title, self.original_title, self.description, self.url, self.cover_url ) )

		# Save (commit) the changes
		conn.commit()

		c.close()
		
	def dbLoadInfo(self):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table (CHANGE THIS)
		c.execute('''create table if not exists movies
		(service text, id text, title text, original_title text, description text, url text, cover_url text, primary key(service, id) )''')

		# Insert a row of data
		c.execute("select * from movies where id = ? and service = ? ", ( str(self.id), self.service ) )

		for row in c:
			self.title = row[2]
			self.original_title = row[3]
			self.description = row[4]
			self.url = row[5]
			self.cover_url = row[6]
			#Mark
			self._exist_in_db = True

		# Save (commit) the changes
		conn.commit()

		c.close()
		
		return self._exist_in_db


	
	##----------------------------------------------------------
	##	Sources
	##----------------------------------------------------------	
	def dbDeleteAllSources(self):
		
		conn = self._mcData.dbconn

		c = conn.cursor()

		c.execute('''create table if not exists sources
		(service text, id text, url text, server text, definition text, audio_lang text, primary key(service, id, url, definition, audio_lang) )''')
		
		# Delete
		c.execute("delete from sources where id = ? and service = ?;", (self.id , self.service) )

		# Save (commit) the changes
		conn.commit()
		
		c.close()
		

	def dbStoreSource(self, source):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table
		c.execute('''create table if not exists sources
		(service text, id text, url text, server text, definition text, audio_lang text, primary key(service, id, url, definition, audio_lang) )''')
		
		# Insert a row of data
		c.execute("replace into sources values ( ?, ?, ?, ?, ?, ?)" , (source.service, source.id, source.url, source.server, source.definition, source.audio_lang ) )

		# Save (commit) the changes
		conn.commit()

		c.close()
		

	def dbLoadSources(self):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table (CHANGE THIS)
		c.execute('''create table if not exists sources
		(service text, id text, url text, server text, definition text, audio_lang text, primary key(service, id, url, definition, audio_lang) )''')

		# Select rows of data
		c.execute("select * from sources where id = ? and service = ? ", ( str(self.id), self.service ) )
		
		for row in c:
			s = mcSource()
			s.service = self.service
			s.id = self.id
			s.url = row[2]
			s.server = row[3]
			s.definition = row[4]
			s.audio_lang = row[5]
			self.sources.append(s)
			
			#~ if not self.dbExistSource(s.server, s.definition,  s.audio_lang):
				#~ return false
			
		c.close()

		if len(self.sources) > 0:
			return True
		else:
			return False
	

	def dbExistSource(self, source):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table (CHANGE THIS)
		c.execute('''create table if not exists sources
		(service text, id text, url text, server text, definition text, audio_lang text, primary key(service, id, url, definition, audio_lang) )''')

		# Select rows of data
		query = " select url from sources where id = '%s' and service = '%s' and server = '%s' and definition = '%s' and audio_lang = '%s' and not url = '' LIMIT 1 " % ( str(self.id), source.service , source.server, source.definition,  source.audio_lang ) 
		
		#print query
		sql = c.execute(query)
		
		#sql = c.execute("select url from sources where id = ? and service = ? and server = ? and definition = ? and audio_lang = ? LIMIT 1", ( str(self.id), source.service , source.server, source.definition,  source.audio_lang ) )
		
		rows = c.fetchone()
		
		if rows == None:
			return False
			
		result = rows[0] 
		#print result
		
		c.close()
		
		#print result.find('http')
		
		if result.find('http') == 0:
			return result
		else:
			return False			







	##----------------------------------------------------------
	##	Subtitles
	##----------------------------------------------------------
	def dbStoreSubtitle(self, subtitle):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table
		c.execute('''create table if not exists subtitles
		(service text, id text, url text, server text, definition text, audio_lang text, lang text, primary key(service, id, url, definition, audio_lang, lang) )''')
		
		# Insert a row of data
		c.execute("replace into subtitles values ( ?, ?, ?, ?, ?, ?, ?)" , (subtitle.service, subtitle.id, subtitle.url, subtitle.server, subtitle.definition, subtitle.audio_lang, subtitle.lang ) )

		# Save (commit) the changes
		conn.commit()

		c.close()
		


	def dbLoadSubtitles(self):
		conn = self._mcData.dbconn
		
		c = conn.cursor()

		# Create table (CHANGE THIS)
		c.execute('''create table if not exists subtitles
		(service text, id text, url text, server text, definition text, audio_lang text, lang text, primary key(service, id, url, definition, audio_lang, lang) )''')

		# Select rows of data
		c.execute("select * from subtitles where id = ? and service = ? ", ( str(self.id), self.service ) )
		
		for row in c:
			s = mcSubtitle()
			s.service = self.service
			s.id = self.id
			s.url = row[2]
			s.server = row[3]
			s.definition = row[4]
			s.audio_lang = row[5]
			s.lang = row[6]
			self.subtitles.append(s)
			
		c.close()

		if len(self.subtitles) > 0:
			return True
		else:
			return False





	##----------------------------------------------------------
	##	Audios
	##----------------------------------------------------------
	def dbStoreAudio(self, audio):
		conn = self._mcData.dbconn

		c = conn.cursor()

		# Create table
		c.execute('''create table if not exists audios
		(service text, id text, lang text, primary key(service, id, lang) )''')
		
		# Insert a row of data
		c.execute("replace into audios values ( ?, ?, ? )" , (audio.service, audio.id, audio.lang) )

		# Save (commit) the changes
		conn.commit()

		c.close()
		


	def dbLoadAudios(self):
		conn = self._mcData.dbconn
		
		c = conn.cursor()

		# Create table (CHANGE THIS)
		# Create table
		c.execute('''create table if not exists audios
		(service text, id text, lang text, primary key(service, id, lang) )''')

		# Select rows of data
		c.execute("select * from audios where id = ? and service = ? ", ( str(self.id), self.service ) )
		
		for row in c:
			s = mcAudio()
			s.service = self.service
			s.id = self.id			
			s.lang = row[2]
			self.audios.append(s)
			
		c.close()

		if len(self.audios) > 0:
			return True
		else:
			return False





	###############################
	##	Class Methods
	###############################

	@staticmethod
	def search(name):
		result = []
		return result

	@staticmethod
	def news():
		result = []
		return result

	@staticmethod
	def featured():
		result = []
		return result

class mcSource:
	service         = ""
	id		= ""
	url		= ""
	server		= ""
	definition 	= ""
	is_hd		= False
	audio_lang 	= ""

class mcSubtitle:
	service         = ""
	id		= ""
	url		= ""
	server		= ""
	definition 	= ""
	is_hd		= False
	audio_lang 	= ""
	lang 	= ""	
class mcAudio:
	service         = ""
	id		= ""	
	lang 	= ""


class mcDown:
	
	"""
	EVENTS
	
	-Messages
	-Captcha	
	-File Progresss down
	
	"""

	gui_name = "console"
	def set_gui(self, gui_name):
		self.gui_name = gui_name

	@classmethod
	def wait(cls, delay):		
		m = __import__ ( 'gui_' + cls.gui_name )
		methodToCall = getattr(m, cls.gui_name + '_wait')
		return methodToCall(delay)
	
	@classmethod
	def show_captcha(cls, url):
		m = __import__ ( 'gui_' + cls.gui_name )
		methodToCall = getattr(m, cls.gui_name + '_show_captcha')
		return methodToCall(url)
	
	#def reCaptcha(cls, key, url_base, cf = None, headers = None):	
		
	@classmethod	
	def reCaptcha(cls, key, cf = None):

		print "Captcha\n"
		logger = mcLogger.getInstance('recaptcha')
		
		#http://www.google.com/recaptcha/api/challenge?k=6LdNWbsSAAAAAIMksu-X7f5VgYy8bZiiJzlP83Rl&ajax=1&cachestop=0.7858106532293022
		url = "http://www.google.com/recaptcha/api/challenge?k="+key+"&ajax=1&cachestop=0.7858106532293022"

		salida = mcScrapper.get(url, cf)

		#Server
		SERVER=""
		rec_server = re.compile('server[[\s?]:[\s?]\'([^\']*)\'')
		match = re.search(rec_server, salida)

		if match != None:
		    SERVER=match.group(1)

		#Server
		SERVER=""
		rec_server = re.compile('server[[\s?]:[\s?]\'([^\']*)\'')
		match = re.search(rec_server, salida)

		if match != None:
		    SERVER=match.group(1)

		#Server
		CHALLENGE=""
		rec_challenge = re.compile('challenge[[\s?]:[\s?]\'([^\']*)\'')
		match = re.search(rec_challenge, salida)

		if match != None:
		    CHALLENGE=match.group(1)

		FILENAME = "recaptcha.jpg"    

		URL=SERVER + "image?c=" + CHALLENGE   

		captcha = cls.show_captcha(URL)

		data = {

		'recaptcha_response_field': captcha,	
		'recaptcha_challenge_field': CHALLENGE

		}

		post = urllib.urlencode(data)

		print "\nCaptcha:"
		print captcha

		print "\nChallenge:"
		print CHALLENGE
		
		print "\n"
		
		return post
		
		#~ if headers == None:
			#~ headers = { 'X-Requested-With': 'XMLHttpRequest', 'Referer': url_base }
		
		#~ #post
		#~ salida = mcScrapper.post(url_base, post, cf, headers)
		#~ return salida	


class mcLang:

	isoLangs = {
	"ab":{
	"name_ES":"",
	"name":"Abkhaz",
	"nativeName":"аҧсуа"
	},
	"aa":{
	"name_ES":"",
	"name":"Afar",
	"nativeName":"Afaraf"
	},
	"af":{
	"name_ES":"",
	"name":"Afrikaans",
	"nativeName":"Afrikaans"
	},
	"ak":{
	"name_ES":"",
	"name":"Akan",
	"nativeName":"Akan"
	},
	"sq":{
	"name_ES":"",
	"name":"Albanian",
	"nativeName":"Shqip"
	},
	"am":{
	"name_ES":"",
	"name":"Amharic",
	"nativeName":"አማርኛ"
	},
	"ar":{
	"name_ES":"Arabe",
	"name":"Arabic",
	"nativeName":"العربية"
	},
	"an":{
	"name_ES":"Aragonés",
	"name":"Aragonese",
	"nativeName":"Aragonés"
	},
	"hy":{
	"name_ES":"",
	"name":"Armenian",
	"nativeName":"Հայերեն"
	},
	"as":{
	"name_ES":"",
	"name":"Assamese",
	"nativeName":"অসমীয়া"
	},
	"av":{
	"name_ES":"",
	"name":"Avaric",
	"nativeName":"авар мацӀ, магӀарул мацӀ"
	},
	"ae":{
	"name_ES":"",
	"name":"Avestan",
	"nativeName":"avesta"
	},
	"ay":{
	"name_ES":"Aymara",
	"name":"Aymara",
	"nativeName":"aymar aru"
	},
	"az":{
	"name_ES":"",
	"name":"Azerbaijani",
	"nativeName":"azərbaycan dili"
	},
	"bm":{
	"name_ES":"",
	"name":"Bambara",
	"nativeName":"bamanankan"
	},
	"ba":{
	"name_ES":"",
	"name":"Bashkir",
	"nativeName":"башҡорт теле"
	},
	"eu":{
	"name_ES":"",
	"name":"Basque",
	"nativeName":"euskara, euskera"
	},
	"be":{
	"name_ES":"",
	"name":"Belarusian",
	"nativeName":"Беларуская"
	},
	"bn":{
	"name_ES":"",
	"name":"Bengali",
	"nativeName":"বাংলা"
	},
	"bh":{
	"name_ES":"",
	"name":"Bihari",
	"nativeName":"भोजपुरी"
	},
	"bi":{
	"name_ES":"",
	"name":"Bislama",
	"nativeName":"Bislama"
	},
	"bs":{
	"name_ES":"Bosnio",
	"name":"Bosnian",
	"nativeName":"bosanski jezik"
	},
	"br":{
	"name_ES":"",
	"name":"Breton",
	"nativeName":"brezhoneg"
	},
	"bg":{
	"name_ES":"",
	"name":"Bulgarian",
	"nativeName":"български език"
	},
	"my":{
	"name_ES":"",
	"name":"Burmese",
	"nativeName":"ဗမာစာ"
	},
	"ca":{
	"name_ES":"Catalán; Valenciano",
	"name":"Catalan; Valencian",
	"nativeName":"Català"
	},
	"ch":{
	"name_ES":"",
	"name":"Chamorro",
	"nativeName":"Chamoru"
	},
	"ce":{
	"name_ES":"",
	"name":"Chechen",
	"nativeName":"нохчийн мотт"
	},
	"ny":{
	"name_ES":"",
	"name":"Chichewa; Chewa; Nyanja",
	"nativeName":"chiCheŵa, chinyanja"
	},
	"zh":{
	"name_ES":"Chino",
	"name":"Chinese",
	"nativeName":"中文 (Zhōngwén), 汉语, 漢語"
	},
	"cv":{
	"name_ES":"",
	"name":"Chuvash",
	"nativeName":"чӑваш чӗлхи"
	},
	"kw":{
	"name_ES":"",
	"name":"Cornish",
	"nativeName":"Kernewek"
	},
	"co":{
	"name_ES":"",
	"name":"Corsican",
	"nativeName":"corsu, lingua corsa"
	},
	"cr":{
	"name_ES":"",
	"name":"Cree",
	"nativeName":"ᓀᐦᐃᔭᐍᐏᐣ"
	},
	"hr":{
	"name_ES":"Croata",
	"name":"Croatian",
	"nativeName":"hrvatski"
	},
	"cs":{
	"name_ES":"Checho",
	"name":"Czech",
	"nativeName":"česky, čeština"
	},
	"da":{
	"name_ES":"Danés",
	"name":"Danish",
	"nativeName":"dansk"
	},
	"dv":{
	"name_ES":"",
	"name":"Divehi; Dhivehi; Maldivian;",
	"nativeName":"ދިވެހި"
	},
	"nl":{
	"name_ES":"Neerlandés; Holandés",
	"name":"Dutch",
	"nativeName":"Nederlands, Vlaams"
	},
	"en":{
	"name_ES":"Inglés",
	"name":"English",
	"nativeName":"English"
	},
	"eo":{
	"name_ES":"",
	"name":"Esperanto",
	"nativeName":"Esperanto"
	},
	"et":{
	"name_ES":"Estón",
	"name":"Estonian",
	"nativeName":"eesti, eesti keel"
	},
	"ee":{
	"name_ES":"",
	"name":"Ewe",
	"nativeName":"Eʋegbe"
	},
	"fo":{
	"name_ES":"",
	"name":"Faroese",
	"nativeName":"føroyskt"
	},
	"fj":{
	"name_ES":"",
	"name":"Fijian",
	"nativeName":"vosa Vakaviti"
	},
	"fi":{
	"name_ES":"Finés",
	"name":"Finnish",
	"nativeName":"suomi, suomen kieli"
	},
	"fr":{
	"name_ES":"Francés",
	"name":"French",
	"nativeName":"français, langue française"
	},
	"ff":{
	"name_ES":"",
	"name":"Fula; Fulah; Pulaar; Pular",
	"nativeName":"Fulfulde, Pulaar, Pular"
	},
	"gl":{
	"name_ES":"Gallego",
	"name":"Galician",
	"nativeName":"Galego"
	},
	"ka":{
	"name_ES":"",
	"name":"Georgian",
	"nativeName":"ქართული"
	},
	"de":{
	"name_ES":"Alemán",
	"name":"German",
	"nativeName":"Deutsch"
	},
	"el":{
	"name_ES":"Griego",
	"name":"Greek, Modern",
	"nativeName":"Ελληνικά"
	},
	"gn":{
	"name_ES":"Guaraní",
	"name":"Guaraní",
	"nativeName":"Avañeẽ"
	},
	"gu":{
	"name_ES":"",
	"name":"Gujarati",
	"nativeName":"ગુજરાતી"
	},
	"ht":{
	"name_ES":"",
	"name":"Haitian; Haitian Creole",
	"nativeName":"Kreyòl ayisyen"
	},
	"ha":{
	"name_ES":"",
	"name":"Hausa",
	"nativeName":"Hausa, هَوُسَ"
	},
	"he":{
	"name_ES":"Hebreo",
	"name":"Hebrew (modern)",
	"nativeName":"עברית"
	},
	"hz":{
	"name_ES":"",
	"name":"Herero",
	"nativeName":"Otjiherero"
	},
	"hi":{
	"name_ES":"Hindi",
	"name":"Hindi",
	"nativeName":"हिन्दी, हिंदी"
	},
	"ho":{
	"name_ES":"",
	"name":"Hiri Motu",
	"nativeName":"Hiri Motu"
	},
	"hu":{
	"name_ES":"Húngaro",
	"name":"Hungarian",
	"nativeName":"Magyar"
	},
	"ia":{
	"name_ES":"",
	"name":"Interlingua",
	"nativeName":"Interlingua"
	},
	"id":{
	"name_ES":"",
	"name":"Indonesian",
	"nativeName":"Bahasa Indonesia"
	},
	"ie":{
	"name_ES":"",
	"name":"Interlingue",
	"nativeName":"Originally called Occidental; then Interlingue after WWII"
	},
	"ga":{
	"name_ES":"",
	"name":"Irish",
	"nativeName":"Gaeilge"
	},
	"ig":{
	"name_ES":"",
	"name":"Igbo",
	"nativeName":"Asụsụ Igbo"
	},
	"ik":{
	"name_ES":"",
	"name":"Inupiaq",
	"nativeName":"Iñupiaq, Iñupiatun"
	},
	"io":{
	"name_ES":"",
	"name":"Ido",
	"nativeName":"Ido"
	},
	"is":{
	"name_ES":"",
	"name":"Icelandic",
	"nativeName":"Íslenska"
	},
	"it":{
	"name_ES":"Italiano",
	"name":"Italian",
	"nativeName":"Italiano"
	},
	"iu":{
	"name_ES":"",
	"name":"Inuktitut",
	"nativeName":"ᐃᓄᒃᑎᑐᑦ"
	},
	"ja":{
	"name_ES":"Japonés",
	"name":"Japanese",
	"nativeName":"日本語 (にほんご／にっぽんご)"
	},
	"jv":{
	"name_ES":"",
	"name":"Javanese",
	"nativeName":"basa Jawa"
	},
	"kl":{
	"name_ES":"",
	"name":"Kalaallisut, Greenlandic",
	"nativeName":"kalaallisut, kalaallit oqaasii"
	},
	"kn":{
	"name_ES":"",
	"name":"Kannada",
	"nativeName":"ಕನ್ನಡ"
	},
	"kr":{
	"name_ES":"",
	"name":"Kanuri",
	"nativeName":"Kanuri"
	},
	"ks":{
	"name_ES":"",
	"name":"Kashmiri",
	"nativeName":"कश्मीरी, كشميري‎"
	},
	"kk":{
	"name_ES":"",
	"name":"Kazakh",
	"nativeName":"Қазақ тілі"
	},
	"km":{
	"name_ES":"",
	"name":"Khmer",
	"nativeName":"ភាសាខ្មែរ"
	},
	"ki":{
	"name_ES":"",
	"name":"Kikuyu, Gikuyu",
	"nativeName":"Gĩkũyũ"
	},
	"rw":{
	"name_ES":"",
	"name":"Kinyarwanda",
	"nativeName":"Ikinyarwanda"
	},
	"ky":{
	"name_ES":"",
	"name":"Kirghiz, Kyrgyz",
	"nativeName":"кыргыз тили"
	},
	"kv":{
	"name_ES":"",
	"name":"Komi",
	"nativeName":"коми кыв"
	},
	"kg":{
	"name_ES":"",
	"name":"Kongo",
	"nativeName":"KiKongo"
	},
	"ko":{
	"name_ES":"Coreano",
	"name":"Korean",
	"nativeName":"한국어 (韓國語), 조선말 (朝鮮語)"
	},
	"ku":{
	"name_ES":"",
	"name":"Kurdish",
	"nativeName":"Kurdî, كوردی‎"
	},
	"kj":{
	"name_ES":"",
	"name":"Kwanyama, Kuanyama",
	"nativeName":"Kuanyama"
	},
	"la":{
	"name_ES":"",
	"name":"Latin",
	"nativeName":"latine, lingua latina"
	},
	"lb":{
	"name_ES":"",
	"name":"Luxembourgish, Letzeburgesch",
	"nativeName":"Lëtzebuergesch"
	},
	"lg":{
	"name_ES":"",
	"name":"Luganda",
	"nativeName":"Luganda"
	},
	"li":{
	"name_ES":"",
	"name":"Limburgish, Limburgan, Limburger",
	"nativeName":"Limburgs"
	},
	"ln":{
	"name_ES":"",
	"name":"Lingala",
	"nativeName":"Lingála"
	},
	"lo":{
	"name_ES":"",
	"name":"Lao",
	"nativeName":"ພາສາລາວ"
	},
	"lt":{
	"name_ES":"",
	"name":"Lithuanian",
	"nativeName":"lietuvių kalba"
	},
	"lu":{
	"name_ES":"",
	"name":"Luba-Katanga",
	"nativeName":""
	},
	"lv":{
	"name_ES":"",
	"name":"Latvian",
	"nativeName":"latviešu valoda"
	},
	"gv":{
	"name_ES":"",
	"name":"Manx",
	"nativeName":"Gaelg, Gailck"
	},
	"mk":{
	"name_ES":"",
	"name":"Macedonian",
	"nativeName":"македонски јазик"
	},
	"mg":{
	"name_ES":"",
	"name":"Malagasy",
	"nativeName":"Malagasy fiteny"
	},
	"ms":{
	"name_ES":"",
	"name":"Malay",
	"nativeName":"bahasa Melayu, بهاس ملايو‎"
	},
	"ml":{
	"name_ES":"",
	"name":"Malayalam",
	"nativeName":"മലയാളം"
	},
	"mt":{
	"name_ES":"",
	"name":"Maltese",
	"nativeName":"Malti"
	},
	"mi":{
	"name_ES":"",
	"name":"Māori",
	"nativeName":"te reo Māori"
	},
	"mr":{
	"name_ES":"",	
	"name":"Marathi (Marāṭhī)",
	"nativeName":"मराठी"
	},
	"mh":{
	"name_ES":"",
	"name":"Marshallese",
	"nativeName":"Kajin M̧ajeļ"
	},
	"mn":{
	"name_ES":"Mongol",
	"name":"Mongolian",
	"nativeName":"монгол"
	},
	"na":{
	"name_ES":"",
	"name":"Nauru",
	"nativeName":"Ekakairũ Naoero"
	},
	"nv":{
	"name_ES":"",
	"name":"Navajo, Navaho",
	"nativeName":"Diné bizaad, Dinékʼehǰí"
	},
	"nb":{
	"name_ES":"",
	"name":"Norwegian Bokmål",
	"nativeName":"Norsk bokmål"
	},
	"nd":{
	"name_ES":"",
	"name":"North Ndebele",
	"nativeName":"isiNdebele"
	},
	"ne":{
	"name_ES":"Nepalés",
	"name":"Nepali",
	"nativeName":"नेपाली"
	},
	"ng":{
	"name_ES":"",
	"name":"Ndonga",
	"nativeName":"Owambo"
	},
	"nn":{
	"name_ES":"",
	"name":"Norwegian Nynorsk",
	"nativeName":"Norsk nynorsk"
	},
	"no":{
	"name_ES":"Noruego",
	"name":"Norwegian",
	"nativeName":"Norsk"
	},
	"ii":{
	"name_ES":"",
	"name":"Nuosu",
	"nativeName":"ꆈꌠ꒿ Nuosuhxop"
	},
	"nr":{
	"name_ES":"",
	"name":"South Ndebele",
	"nativeName":"isiNdebele"
	},
	"oc":{
	"name_ES":"",
	"name":"Occitan",
	"nativeName":"Occitan"
	},
	"oj":{
	"name_ES":"",
	"name":"Ojibwe, Ojibwa",
	"nativeName":"ᐊᓂᔑᓈᐯᒧᐎᓐ"
	},
	"cu":{
	"name_ES":"",
	"name":"Old Church Slavonic, Church Slavic, Church Slavonic, Old Bulgarian, Old Slavonic",
	"nativeName":"ѩзыкъ словѣньскъ"
	},
	"om":{
	"name_ES":"",
	"name":"Oromo",
	"nativeName":"Afaan Oromoo"
	},
	"or":{
	"name_ES":"",
	"name":"Oriya",
	"nativeName":"ଓଡ଼ିଆ"
	},
	"os":{
	"name_ES":"",
	"name":"Ossetian, Ossetic",
	"nativeName":"ирон æвзаг"
	},
	"pa":{
	"name_ES":"",
	"name":"Panjabi, Punjabi",
	"nativeName":"ਪੰਜਾਬੀ, پنجابی‎"
	},
	"pi":{
	"name_ES":"",
	"name":"Pāli",
	"nativeName":"पाऴि"
	},
	"fa":{
	"name_ES":"Iraní",
	"name":"Persian",
	"nativeName":"فارسی"
	},
	"pl":{
	"name_ES":"Polaco",
	"name":"Polish",
	"nativeName":"polski"
	},
	"ps":{
	"name_ES":"",
	"name":"Pashto, Pushto",
	"nativeName":"پښتو"
	},
	"pt":{
	"name_ES":"Portugués",
	"name":"Portuguese",
	"nativeName":"Português"
	},
	"qu":{
	"name_ES":"Quechua",
	"name":"Quechua",
	"nativeName":"Runa Simi, Kichwa"
	},
	"rm":{
	"name_ES":"",
	"name":"Romansh",
	"nativeName":"rumantsch grischun"
	},
	"rn":{
	"name_ES":"",
	"name":"Kirundi",
	"nativeName":"kiRundi"
	},
	"ro":{
	"name_ES":"Rumano",
	"name":"Romanian, Moldavian, Moldovan",
	"nativeName":"română"
	},
	"ru":{
	"name_ES":"Ruso",
	"name":"Russian",
	"nativeName":"русский язык"
	},
	"sa":{
	"name_ES":"",
	"name":"Sanskrit (Saṁskṛta)",
	"nativeName":"संस्कृतम्"
	},
	"sc":{
	"name_ES":"",
	"name":"Sardinian",
	"nativeName":"sardu"
	},
	"sd":{
	"name_ES":"",
	"name":"Sindhi",
	"nativeName":"सिन्धी, سنڌي، سندھی‎"
	},
	"se":{
	"name_ES":"",
	"name":"Northern Sami",
	"nativeName":"Davvisámegiella"
	},
	"sm":{
	"name_ES":"",
	"name":"Samoan",
	"nativeName":"gagana faa Samoa"
	},
	"sg":{
	"name_ES":"",
	"name":"Sango",
	"nativeName":"yângâ tî sängö"
	},
	"sr":{
	"name_ES":"Serbio",
	"name":"Serbian",
	"nativeName":"српски језик"
	},
	"gd":{
	"name_ES":"",
	"name":"Scottish Gaelic; Gaelic",
	"nativeName":"Gàidhlig"
	},
	"sn":{
	"name_ES":"",
	"name":"Shona",
	"nativeName":"chiShona"
	},
	"si":{
	"name_ES":"",
	"name":"Sinhala, Sinhalese",
	"nativeName":"සිංහල"
	},
	"sk":{
	"name_ES":"",
	"name":"Slovak",
	"nativeName":"slovenčina"
	},
	"sl":{
	"name_ES":"Esloveno",
	"name":"Slovene",
	"nativeName":"slovenščina"
	},
	"so":{
	"name_ES":"",
	"name":"Somali",
	"nativeName":"Soomaaliga, af Soomaali"
	},
	"st":{
	"name_ES":"",
	"name":"Southern Sotho",
	"nativeName":"Sesotho"
	},
	"es":{
	"name_ES":"Español; Castellano",
	"name":"Spanish; Castilian",
	"nativeName":"español, castellano"
	},
	"su":{
	"name_ES":"",
	"name":"Sundanese",
	"nativeName":"Basa Sunda"
	},
	"sw":{
	"name_ES":"",
	"name":"Swahili",
	"nativeName":"Kiswahili"
	},
	"ss":{
	"name_ES":"",
	"name":"Swati",
	"nativeName":"SiSwati"
	},
	"sv":{
	"name_ES":"Sueco",
	"name":"Swedish",
	"nativeName":"svenska"
	},
	"ta":{
	"name_ES":"",
	"name":"Tamil",
	"nativeName":"தமிழ்"
	},
	"te":{
	"name_ES":"",
	"name":"Telugu",
	"nativeName":"తెలుగు"
	},
	"tg":{
	"name_ES":"",
	"name":"Tajik",
	"nativeName":"тоҷикӣ, toğikī, تاجیکی‎"
	},
	"th":{
	"name_ES":"Tailandés",
	"name":"Thai",
	"nativeName":"ไทย"
	},
	"ti":{
	"name_ES":"",
	"name":"Tigrinya",
	"nativeName":"ትግርኛ"
	},
	"bo":{
	"name_ES":"",
	"name":"Tibetan Standard, Tibetan, Central",
	"nativeName":"བོད་ཡིག"
	},
	"tk":{
	"name_ES":"",
	"name":"Turkmen",
	"nativeName":"Türkmen, Түркмен"
	},
	"tl":{
	"name_ES":"",
	"name":"Tagalog",
	"nativeName":"Wikang Tagalog, ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"
	},
	"tn":{
	"name_ES":"",
	"name":"Tswana",
	"nativeName":"Setswana"
	},
	"to":{
	"name_ES":"",
	"name":"Tonga (Tonga Islands)",
	"nativeName":"faka Tonga"
	},
	"tr":{
	"name_ES":"Turco",
	"name":"Turkish",
	"nativeName":"Türkçe"
	},
	"ts":{
	"name_ES":"",
	"name":"Tsonga",
	"nativeName":"Xitsonga"
	},
	"tt":{
	"name_ES":"",
	"name":"Tatar",
	"nativeName":"татарча, tatarça, تاتارچا‎"
	},
	"tw":{
	"name_ES":"",
	"name":"Twi",
	"nativeName":"Twi"
	},
	"ty":{
	"name_ES":"",
	"name":"Tahitian",
	"nativeName":"Reo Tahiti"
	},
	"ug":{
	"name_ES":"",
	"name":"Uighur, Uyghur",
	"nativeName":"Uyƣurqə, ئۇيغۇرچە‎"
	},
	"uk":{
	"name_ES":"",
	"name":"Ukrainian",
	"nativeName":"українська"
	},
	"ur":{
	"name_ES":"",
	"name":"Urdu",
	"nativeName":"اردو"
	},
	"uz":{
	"name_ES":"",
	"name":"Uzbek",
	"nativeName":"zbek, Ўзбек, أۇزبېك‎"
	},
	"ve":{
	"name_ES":"",
	"name":"Venda",
	"nativeName":"Tshivenḓa"
	},
	"vi":{
	"name_ES":"",
	"name":"Vietnamese",
	"nativeName":"Tiếng Việt"
	},
	"vo":{
	"name_ES":"",
	"name":"Volapük",
	"nativeName":"Volapük"
	},
	"wa":{
	"name_ES":"",
	"name":"Walloon",
	"nativeName":"Walon"
	},
	"cy":{
	"name_ES":"",
	"name":"Welsh",
	"nativeName":"Cymraeg"
	},
	"wo":{
	"name_ES":"",
	"name":"Wolof",
	"nativeName":"Wollof"
	},
	"fy":{
	"name_ES":"",
	"name":"Western Frisian",
	"nativeName":"Frysk"
	},
	"xh":{
	"name_ES":"",
	"name":"Xhosa",
	"nativeName":"isiXhosa"
	},
	"yi":{
	"name_ES":"",
	"name":"Yiddish",
	"nativeName":"ייִדיש"
	},
	"yo":{
	"name_ES":"",
	"name":"Yoruba",
	"nativeName":"Yorùbá"
	},
	"za":{
	"name_ES":"",
	"name":"Zhuang, Chuang",
	"nativeName":"Saɯ cueŋƅ, Saw cuengh"
	}
	
	
	,
	"cmn":{
	"name_ES":"Mandarín",
	"name":"Mandarin Chinese",
	"nativeName":""
	}
	,
	"yue":{
	"name_ES":"Cantonés",
	"name":"Yue Chinese",
	"nativeName":""
	}

	
	
	}

	@classmethod
	def getNameFromCode(cls, code):
		return cls.isoLangs[code]['name']

	@classmethod
	def getName_ESFromCode(cls, code):
		return cls.isoLangs[code.lower()]['name_ES']
	
	
	@classmethod
	def getCodeFromName(cls, name):
		for code in cls.isoLangs:			
			names = cls.isoLangs[code]['name'].lower().split(';')
			if name.lower() in names:
				return code.upper()			
		return False

	@classmethod
	def getCodeFromName_ES(cls, name):
		
		for code in cls.isoLangs:			
			
			names = cls.isoLangs[code]['name_ES'].lower().split(';')
			if name.lower() in names:
				return code.upper()			
		return False

